package com.ok.common.ext

import android.content.Context
import android.view.inputmethod.InputMethodManager
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.ok.common.R

/**
 * 向FragmentManager添加Fragment
 */
fun FragmentManager.add(
    fragment: Fragment,
    containerId: Int,
    addToBackStack: Boolean = true,
    anim: Boolean = false,
    tagName: String? = null
) {
    beginTransaction().apply {
        if (anim) {
            setCustomAnimations(
                R.anim.slide_in_right,
                R.anim.slide_out_left,
                R.anim.slide_in_left,
                R.anim.slide_out_right
            )
        }
        replace(containerId, fragment)
        if (addToBackStack) {
            addToBackStack(tagName)
        }
        commit()
    }
}

/**
 * 向FragmentManager替换Fragment
 */
fun FragmentManager.replace(
    fragment: Fragment,
    containerId: Int,
    anim: Boolean = false,
) {
    add(fragment, containerId, false, anim)
}

/**
 * FragmentManager返回上一个Fragment
 */
fun FragmentManager.pop() {
    popBackStack()
}

fun FragmentManager.popAll() {
    popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
}

fun Fragment.hideKeyboard() {
    val inputMethodManager = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
    val currentFocusedView = activity?.currentFocus
    currentFocusedView?.let {
        inputMethodManager?.hideSoftInputFromWindow(it.windowToken, 0)
    }
}



